package com.wu;

/**
 * 回文串
 */
public class BackChar {

    public static void main(String[] args) {
        boolean isBackChar = validateBackChar("abcddcba");
        System.out.println(isBackChar);

        boolean isBackChar2 = validateBackChar2("abcdcba");
        System.out.println(isBackChar2);
    }

    /**
     * 验证是否是回文串
     *
     * @param content
     * @return
     */
    public static boolean validateBackChar(String content) {
        int length = content.length();
        int middleIndex = length / 2;
        // 是否是偶数个长度的标识
        boolean flag = length % 2 == 0 ? true : false;
        if (flag) {
            String beforeMiddleChar = content.substring(0, middleIndex);
            String afterMiddleChar = content.substring(middleIndex);
            if (new StringBuffer().append(beforeMiddleChar).reverse().toString().equals(afterMiddleChar)) {
                return true;
            }
        } else {
            String beforeMiddleChar = content.substring(0, middleIndex);
            String afterMiddleChar = content.substring(middleIndex + 1);
            if (new StringBuffer().append(beforeMiddleChar).reverse().toString().equals(afterMiddleChar)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 验证是否是回文串
     *
     * @param content
     * @return
     */
    public static boolean validateBackChar2(String content) {
        char[] chars = content.toCharArray();
        int middleIndex = chars.length/ 2;
        for (int i = 0,j=chars.length-1; i < middleIndex; i++,j--) {
            if(chars[i]!=chars[j]){
                return false;
            }
        }
        return true;
    }

}